package com.example.demo.algorithm.symbol;

/**
 * @Author: xiatian
 * @CreateTime: 2021/12/30 3:38 下午
 * @Description:符号表
 */
public class SymbolTable<Key, Value> {
    //记录符号表的首节点
    private Node head;
    //记录符号表中元素的个数
    private int N;

    public SymbolTable() {
        this.head = new Node(null, null, null);
        N = 0;
    }

    /**
     * 符号表中键值对的个数
     *
     * @return
     */
    public int size() {
        return N;
    }

    //往符号表中插入键值对
    public void put(Key key, Value value) {
        //查找符号表中键为key的键值对
        Node n = head.next;
        while (n != null) {
            if (key.equals(n.key)) {
                n.value = value;
                return;
            }
            n = n.next;
        }
        //如果没有找到key的键值对
        Node oldFirst = head.next;
        Node newFirst = new Node(key, value, oldFirst);
        head.next = newFirst;
        N++;
    }

    //删除符号表中键为key的键值对
    public void delete(Key key) {
        Node n = head.next;
        while (n != null) {
            if (n.key.equals(key)) {
                n = n.next;
                N--;
                return;
            }
            n = n.next;
        }
    }

    //从符号表中获取键为key的值
    public Value get(Key key) {
        Node n = head.next;
        while (n != null) {
            if (n.key.equals(key)) {
                return n.value;
            }
            n = n.next;
        }
        return null;
    }


    private class Node {
        private Key key;
        private Value value;
        public Node next;

        public Node(Key key, Value value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
}
